import { getDictOptionsByCode } from '@/support/common';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Row,
  Select,
} from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PageHeaderLayout from '../../../../layouts/PageHeaderLayout';
import styles from './style.less';

const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 0 },
  },
  wrapperCol: {
    xs: { span: 0 },
    sm: { span: 0 },
    md: { span: 0 },
  },
};

const fieldLabels = {
  userName: '用户名称',
  userAccountSid: '用户账号SID',
  userLevel: '用户等级',
  sexuality: '性别',
  mobilePhone: '手机号',
  email: '邮箱',
  address: '地址',
  idType: '证件类型',
  idNo: '证件号',
  driverLicenseNo: '驾驶证号码',
  age: '年龄',
  birthday: '生日',
};

@connect(state => ({
  baseUser: state.baseUser,
}))
// @Form.create()
export default class BaseUserAdd extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.array,
  };
  formRef = React.createRef();
  state = {
    idType: '',
    query: {},
    buttonLoading: false,
  };
  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        query: this.props.location.state.obj,
      });
    }
  }
  componentDidMount() {
    if (this.props.location.state && this.props.location.state.data) {
      const record = this.props.location.state.data;
      this.formRef.current.resetFields();
      this.formRef.current.setFieldsValue({
        sid: record.sid,
        userName: record.userName,
        userAccountSid: record.userAccountSid,
        userLevel: record.userLevel,
        sexuality: record.sexuality == null ? record.sexuality : record.sexuality.toString(),
        mobilePhone: record.mobilePhone,
        oldMobilePhone: record.mobilePhone,
        email: record.email,
        address: record.address,
        idNo: record.idNo,
        driverLicenseNo: record.driverLicenseNo,
        age: record.age,
        birthday: record.birthday ? moment(record.birthday) : '',
        createDate: record.createDate,
        createdBy: record.createdBy,
        delFlag: record.delFlag,
        version: record.version,
      });
      if (record.idType == 0 || record.idType.toString() == '0') {
      } else {
        this.formRef.current.setFieldsValue({
          idType: record.idType == null ? record.idType : record.idType.toString(),
        });
      }
    }
  }
  goBack = () => {
    const { dispatch } = this.props;
    this.formRef.current?.resetFields();
    dispatch(routerRedux.push({ pathname: '/baseUserManager/baseUser' }));
  };
  canceledit = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    this.formRef.current?.resetFields();
    dispatch(routerRedux.push({ pathname: '/baseUserManager/baseUser', state: { query } }));
  };

  render() {
    const { buttonLoading } = this.state;
    const sex = getDictOptionsByCode(this.context.dicData, 'sex');
    const certType = getDictOptionsByCode(this.context.dicData, 'certType');
    const { form, dispatch } = this.props;
    const dateFormat = 'YYYY/MM/DD';
    // const { getFieldDecorator, validateFieldsAndScroll, getFieldsError } = form;
    const validate = () => {
      this.formRef.current.validateFields().then(values => {
        const obj = values;
        // if (values.produceDate) {
        //   obj.produceDate = values.produceDate.format('YYYY-MM-DD HH:mm:ss');
        // }
        if (values.birthday) {
          obj.birthday = values.birthday.format('YYYY-MM-DD');
        }
        // if (!error) {
        this.setState({
          buttonLoading: true,
        });
        const { query } = this.state;
        const url = values.sid ? 'baseUser/edit' : 'baseUser/add';
        dispatch({
          type: url,
          payload: obj,
          callback: response => {
            if (response.code === '200') {
              message.success('操作成功');
              this.formRef.current.resetFields();
              this.setState({
                buttonLoading: false,
              });
              if (url === 'baseUser/edit') {
                dispatch(
                  routerRedux.push({ pathname: '/baseUserManager/baseUser', state: { query } }),
                );
              } else {
                dispatch(routerRedux.push('/baseUserManager/baseUser'));
              }
            } else {
              message.error(response.description, 3);
              // this.props.form.resetFields();
              this.setState({
                buttonLoading: false,
              });
            }
          },
        });
        // }
      });
    };
    // const errors = getFieldsError();
    // const getErrorInfo = () => {
    //   const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    //   if (!errors || errorCount === 0) {
    //     return null;
    //   }
    //   const scrollToField = (fieldKey) => {
    //     const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
    //     if (labelNode) {
    //       labelNode.scrollIntoView(true);
    //     }
    //   };
    //   const errorList = Object.keys(errors).map((key) => {
    //     if (!errors[key]) {
    //       return null;
    //     }
    //     return (
    //       <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
    //         <Icon type="cross-circle-o" className={styles.errorIcon} />
    //         <div className={styles.errorMessage}>{errors[key][0]}</div>
    //         <div className={styles.errorField}>{fieldLabels[key]}</div>
    //       </li>
    //     );
    //   });
    //   return (
    //     <span className={styles.errorIcon}>
    //       <Popover
    //         title="表单校验信息"
    //         content={errorList}
    //         overlayClassName={styles.errorPopover}
    //         trigger="click"
    //         getPopupContainer={trigger => trigger.parentNode}
    //       >
    //         <Icon type="exclamation-circle" />
    //       </Popover>
    //       {errorCount}
    //     </span>
    //   );
    // };
    if (this.props.location.flag) {
      return (
        <PageHeaderLayout title="" wrapperClassName={styles.advancedForm}>
          <Card title="" className={styles.card} bordered={false}>
            <Form layout="vertical" hideRequiredMark ref={this.formRef}>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.userName}
                    name="userName"
                    rules={[
                      { required: true, message: '用户名称' },
                      { max: 50, message: '用户名称不能多于50个字符' },
                    ]}
                  >
                    <Input placeholder="请输入用户名称" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.userLevel}
                    name="userLevel"
                    rules={[
                      { required: true, message: '用户级别' },
                      // { max: 9999, min: 1, message: '用户级别1-9999' },
                    ]}
                  >
                    <InputNumber
                      max={9999}
                      min={1}
                      style={{ width: '100%' }}
                      placeholder="请输入用户级别1-9999"
                    />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.userAccountSid}
                    style={{ display: 'none' }}
                    name="userAccountSid"
                    rules={[{ required: true, message: '用户账户SID' }]}
                  >
                    <Input placeholder="请输入用户账户SID" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.sexuality}
                    name="sexuality"
                    rules={[{ required: false, message: '性别' }]}
                  >
                    <Select placeholder="请选择性别" options={sex}></Select>
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.age}
                    name="age"
                    rules={[{ required: false, message: '年龄' }]}
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      min={1}
                      max={100}
                      placeholder="请输入用户年龄"
                    />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.birthday}
                    name="birthday"
                    rules={[{ required: false, message: '用户生日' }]}
                  >
                    <DatePicker format={dateFormat} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.idType}
                    rules={[{ required: false, message: '证件类型' }]}
                    name="idType"
                  >
                    <Select
                      placeholder="请选择证件类型"
                      onChange={e => {
                        this.setState({ idType: e });
                      }}
                      options={certType}
                    ></Select>
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.idNo}
                    name="idNo"
                    rules={[
                      {
                        required: false,
                        message: '证件号码格式有误',
                        pattern:
                          this.state.idType === 1
                            ? /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
                            : null,
                      },
                    ]}
                  >
                    <Input placeholder="请输入证件号" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.mobilePhone}
                    name="mobilePhone"
                    rules={[
                      {
                        required: true,
                        message: '电话号码有误!',
                        whitespace: true,
                        pattern: /^1[0-9][0-9]\d{8}$/,
                      },
                    ]}
                  >
                    <Input placeholder="请输入手机号" maxLength={11} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={6} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.driverLicenseNo}
                    name="driverLicenseNo"
                    rules={[
                      {
                        required: false,
                        message: '驾驶证有误!',
                        whitespace: true,
                        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                      },
                    ]}
                  >
                    <Input placeholder="请输入用户驾驶证" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.email}
                    name="email"
                    rules={[{ type: 'email', message: '邮箱格式不正确' }]}
                  >
                    <Input placeholder="请输入用户邮箱" />
                  </Form.Item>
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <Form.Item
                    label={fieldLabels.address}
                    name="address"
                    rules={[{ required: false, message: '用户地址' }]}
                  >
                    <Input placeholder="请输入用户地址" />
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col>
                  <Form.Item {...formItemLayout} label="" name="sid" style={{ display: 'none' }}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    name="createDate"
                    style={{ display: 'none' }}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    name="createdBy"
                    style={{ display: 'none' }}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    name="version"
                    style={{ display: 'none' }}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    name="delFlag"
                    style={{ display: 'none' }}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label=""
                    name="oldMobilePhone"
                    style={{ display: 'none' }}
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div>
                    <Button
                      loading={buttonLoading}
                      key="submit"
                      type="primary"
                      size="default"
                      onClick={validate}
                    >
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm title="确定放弃该用户修改吗?" onConfirm={() => this.canceledit()}>
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        </PageHeaderLayout>
      );
    } else {
      return (
        <PageHeaderLayout title="">
          <div align="center" width="100%" height="100%">
            <h2>未选择任何用户,请返回列表选择</h2>
            <a onClick={this.goBack}>返回</a>
          </div>
        </PageHeaderLayout>
      );
    }
  }
}
